package com.lhcai.haweiOD;

/**
 * @author lhcstart
 * @create 2023-03-01 16:21
 */

import java.lang.ref.SoftReference;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * 计算网络信号
 * 网络信号经过传递会逐层衰减，且遇到阻隔物无法直接穿透，在此情况下需要计算某个位置的网络信号值。
 * 注意:网络信号可以绕过阻隔物
 * <p>
 * array[m][n] 的二维数组代表网格地图，
 * array[i][j] = 0代表i行j列是空旷位置;
 * array[i][j] = x(x为正整数)代表i行j列是信号源，信号强度是x;
 * array[i][j] = -1代表i行j列是阻隔物.
 * 信号源只有1个，阻隔物可能有0个或多个
 * 网络信号衰减是上下左右相邻的网格衰减1
 * 现要求输出对应位置的网络信号值。
 */
public class HJ156 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {

            int m = sc.nextInt();
            int n = sc.nextInt();
            int[][] arr = new int[m][n];
            int[] src = new int[2];//数据源
            int[] dst = new int[2];//要获取的位置
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    arr[i][j] = sc.nextInt();
                    if (arr[i][j] > 0) {
                        src[0] = i;
                        src[1] = j;
                    }
                }
            }
            dst[0] = sc.nextInt();
            dst[1] = sc.nextInt();

            int solve = solve(arr, src, dst);
            System.out.println(solve);

        }
    }

    //队列，存放封装好的类
    private static final LinkedList<Block> blocks = new LinkedList<>();

    private static int solve(int[][] arr, int[] src, int[] dst) {

        //获取信号源坐标
        int x = src[0];
        int y = src[1];

        blocks.add(new Block(x, y, arr[x][y]));
        while (blocks.size() > 0) {
            Block block = blocks.removeFirst();
            dfs(arr, block.x, block.y, block.d);

        }


        return arr[dst[0]][dst[1]];
    }

    private static final int[][] dic = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};//上下左右四个方位

    private static void dfs(int[][] arr, int x, int y, int d) {
        for (int[] di : dic) {
            int newX = x + di[0], newY = y + di[1];//上下左右
            if (newX >= 0 && newX < arr.length && newY >= 0 && newY < arr[0].length) {

                int next = arr[newX][newY];

                if (next == 0) {
                    arr[newX][newY] = d - 1;
                }

                if (d > 2 && next != -1) {
                    blocks.add(new Block(newX, newY, d - 1));
                }
            }
        }

    }


    //静态内部类，存储信号，坐标
    private static class Block {
        int x;
        int y;
        int d;

        public Block(int x, int y, int d) {
            this.x = x;
            this.y = y;
            this.d = d;
        }
    }

}
